package com.course.design.controller;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.IoUtil;
import com.course.design.common.Result;
import com.course.design.entity.Wjxx;
import com.course.design.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * 描述:
 *
 * @author qinlianji
 * @create 2020-02-27
 */
@Api(tags = "文件上传下载")
@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Autowired
    private FileService fileService;

    @ApiOperation(value = "上传文件")
    @PostMapping("/file")
    public Result upload(@RequestParam("file") MultipartFile file, @RequestParam(required = false) String cclj) throws IOException {
        String fileName = file.getOriginalFilename();
        // 拿到文件类型
        int index = fileName.lastIndexOf(".");
        String suffix = null;
        if (index < fileName.length() - 1) {
            suffix = fileName.substring(index+1);
        }
        String newName = UUID.randomUUID().toString().replace("-", "")+ "." + suffix;

        Wjxx wjxx = new Wjxx();
        wjxx.setYwjm(fileName);
        wjxx.setCcwjm(newName);
        wjxx.setCclj(cclj);
        File dest = new File(fileService.buildPath(wjxx));
        try {
            // 创建父级目录
            File parent = dest.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            dest.createNewFile();
            file.transferTo(dest);
            wjxx.setWjdx(file.getSize());
            // 获取文件真实类型
//            wjxx.setWjlx(FileTypeUtil.getType(dest));
            wjxx.setWjlx(suffix);
            fileService.save(wjxx);
            return Result.success(wjxx);
        } catch (Exception e) {
            return Result.fail("文件上传失败！");
        }
    }

    @ApiOperation(value = "文件下载")
    @GetMapping("/download/{wjxxbsId}")
    public void download(@PathVariable String wjxxbsId, HttpServletResponse resp) throws IOException {
        Wjxx wjxx = fileService.queryById(wjxxbsId);
        InputStream fileIn = fileService.getFileStream(wjxx);
        resp.setContentType("application/force-download");
        resp.setHeader("Content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(wjxx.getYwjm(), "UTF-8"));
        OutputStream out = resp.getOutputStream();
        IoUtil.copy(fileIn, out, IoUtil.DEFAULT_BUFFER_SIZE);
        out.flush();
   }
}
